package com.bicntech.admin.controller.airport;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.bicntech.common.annotation.RepeatSubmit;
import com.bicntech.common.core.controller.SuperController;
import com.bicntech.common.core.domain.R;
import com.bicntech.common.enums.InspectStateEnum;
import com.bicntech.system.entity.*;
import com.bicntech.system.service.*;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 更新初始化
 *
 * @author : JMY
 * @create 2023/8/10 17:16
 */
@Api(tags = "更新初始化")
@Slf4j
@ApiIgnore
@RestController
@RequestMapping("/initialize")
public class InitializeController extends SuperController {

    @Resource
    private PersonnelPerformanceManagementService personnelPerformanceManagementService;

    @Resource
    private InfieldVehicleEquipmentInspectService infieldVehicleEquipmentInspectService;

    @Resource
    private OutfieldVehicleEquipmentInspectService outfieldVehicleEquipmentInspectService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private VehicleRefuelingStatisticsService vehicleRefuelingStatisticsService;


    @ApiOperation("初始化绩效统计")
    @GetMapping("/initializePerformance")
    @RepeatSubmit(message = "不允许重复操作", interval = 8, timeUnit = TimeUnit.MINUTES)
    @Transactional(rollbackFor = Exception.class)
    public R<?> initializePerformance() {
        //判断是否可以执行初始化
        Date date = new Date();
        String endYears = DateUtil.format(date, "yyyy-MM");
        DateTime startDateTime = DateUtil.offsetDay(date, -31);
        String startYears = DateUtil.format(startDateTime, "yyyy-MM");
        boolean isExist = personnelPerformanceManagementService
                .lambdaQuery()
                .in(PersonnelPerformanceManagement::getYears, ImmutableList.of(endYears, startYears))
                .exists();
        if (isExist) return R.ok("已存在绩效，执行结束！");
        //初始化外场绩效
        List<UserInfo> userInfoList = userInfoService.list();
        ImmutableMap<String, UserInfo> userInfoImmutableMap = Maps.uniqueIndex(userInfoList, UserInfo::getUserName);
        List<OutfieldVehicleEquipmentInspect> outfieldVehicleEquipmentInspects = outfieldVehicleEquipmentInspectService
                .lambdaQuery()
                .select(OutfieldVehicleEquipmentInspect::getId,
                        OutfieldVehicleEquipmentInspect::getState,
                        OutfieldVehicleEquipmentInspect::getInspectDate,
                        OutfieldVehicleEquipmentInspect::getType,
                        OutfieldVehicleEquipmentInspect::getWorker,
                        OutfieldVehicleEquipmentInspect::getReviewer)
                .in(OutfieldVehicleEquipmentInspect::getState, InspectStateEnum.HISTORY.getDescription(), InspectStateEnum.TO_BE_REVIEWED.getDescription())
                .ge(OutfieldVehicleEquipmentInspect::getInspectDate, startDateTime)
                .le(OutfieldVehicleEquipmentInspect::getInspectDate, date)
                .list();
        for (OutfieldVehicleEquipmentInspect equipmentInspect : outfieldVehicleEquipmentInspects) {
            Optional.ofNullable(equipmentInspect.getWorker())
                    .filter(StrUtil::isNotBlank)
                    .map(userInfoImmutableMap::get)
                    .map(UserInfo::getUserId)
                    .ifPresent(equipmentInspect::setWorkerId);
            Optional.ofNullable(equipmentInspect.getReviewer())
                    .filter(StrUtil::isNotBlank)
                    .map(userInfoImmutableMap::get)
                    .map(UserInfo::getUserId)
                    .ifPresent(equipmentInspect::setReviewerId);
            if (InspectStateEnum.HISTORY.getDescription().equals(equipmentInspect.getState())) {
                personnelPerformanceManagementService.addMark(equipmentInspect.getWorkerId(),
                        2,
                        Long.valueOf(equipmentInspect.getType()),
                        equipmentInspect.getInspectDate());
                personnelPerformanceManagementService.addMark(equipmentInspect.getReviewerId(),
                        2,
                        Long.valueOf(equipmentInspect.getType()),
                        equipmentInspect.getInspectDate());
            }
        }
        CollUtil.split(outfieldVehicleEquipmentInspects, 100)
                .forEach(a -> outfieldVehicleEquipmentInspectService.updateBatchById(a));
        boolean exists = vehicleRefuelingStatisticsService.lambdaQuery()
                .eq(VehicleRefuelingStatistics::getYear, DateUtil.year(date))
                .in(VehicleRefuelingStatistics::getMonth, DateUtil.month(date) + 1, DateUtil.month(startDateTime) + 1)
                .exists();

        //初始化内场绩效及汽车加油量
        List<InfieldVehicleEquipmentInspect> inspectList = infieldVehicleEquipmentInspectService
                .lambdaQuery()
                .select(InfieldVehicleEquipmentInspect::getId,
                        InfieldVehicleEquipmentInspect::getInspectDate,
                        InfieldVehicleEquipmentInspect::getSignatureOfInspectorId,
                        InfieldVehicleEquipmentInspect::getType,
                        InfieldVehicleEquipmentInspect::getWagonNumber,
                        InfieldVehicleEquipmentInspect::getRefuelingVolume)
                .ge(InfieldVehicleEquipmentInspect::getInspectDate, startDateTime)
                .le(InfieldVehicleEquipmentInspect::getInspectDate, date)
                .list();
        for (InfieldVehicleEquipmentInspect vehicleEquipmentInspect : inspectList) {
            if (!exists) {
                //燃油新增
                vehicleRefuelingStatisticsService.addRefueling(vehicleEquipmentInspect.getWagonNumber()
                        , vehicleEquipmentInspect.getInspectDate()
                        , vehicleEquipmentInspect.getRefuelingVolume());
            }
            personnelPerformanceManagementService.addMark(vehicleEquipmentInspect.getSignatureOfInspectorId(),
                    1,
                    vehicleEquipmentInspect.getType(),
                    vehicleEquipmentInspect.getInspectDate());
        }
        return R.ok("操作完成");
    }
}
